package com.jsj.servlet.gb;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsj.dao.IMessageDao;
import com.jsj.dao.IUserDao;
import com.jsj.dao.impl.MessageDaoImpl;
import com.jsj.dao.impl.UserDaoImpl;
import com.jsj.model.Message;
/**
 * 逻辑分页
 * @author Administrator
 *
 */
@WebServlet("/index2")
public class IndexServlet2 extends HttpServlet {
	
	private IMessageDao messageDao=new MessageDaoImpl();
	
	private IUserDao userDao=new UserDaoImpl();

	private static final long serialVersionUID = -3117083193593165442L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");	
		
		List<Message> messageList=messageDao.getAll();
		
		for(Message m:messageList) {
			if(m.getUserId()!=null) {
				m.setUsername(userDao.get(m.getUserId()).getUsername());
			}
		}
		//当前页
		String p=request.getParameter("page");
		int page;
		try {
			page=Integer.valueOf(p);
		} catch (Exception e) {
			page=1;
		}
		//总记录数
		int totalRecords=messageList.size();
		//每页记录数
		int pageSize=3;
		//总页数
		int totalPages=totalRecords % pageSize ==0 ? totalRecords / pageSize : totalRecords / pageSize +1;
		//某页开始记录索引
		int beginIndex=(page-1)*pageSize;
		//某页结束的记录索引
		int endIndex=beginIndex+pageSize;  
		if(endIndex>totalRecords) {
			endIndex=totalRecords;
		}
		
		request.setAttribute("page", page);
		request.setAttribute("totalRecords", totalRecords);
		request.setAttribute("pageSize", pageSize);
		request.setAttribute("totalPages", totalPages);
		request.setAttribute("beginIndex", beginIndex);
		request.setAttribute("endIndex", endIndex);
		request.setAttribute("messageList", messageList);
		
		RequestDispatcher dispatcher=request.getRequestDispatcher("index.jsp");
		dispatcher.forward(request,response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doPost(request, response);
	}
}
